<template>
  <div class="hello">
    <el-upload accept="accept"
      list-type="picture-card"
      :show-file-list='false'
      class="uploader"
      action=""
      :auto-upload='false'
      :on-success="handleSuccess"
      :on-change="handleChange" 
      :before-upload="handleBeforeUpload"
      style="display: inline-block; vertical-align: top">
      <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width:148;height:148px;" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import { getAliyunConfig } from '@/api/upload/config'
import OSS from 'ali-oss'
export default {
  name: 'UploadImage',
  props: {
    handleSuccess: {
      type: Function,
      default: () => {}
    },
    accept : {
      type : 'String',
      required : false
    }
  },
  data () {
    return {
      imageUrl: ''
    }
  },
  methods: {
    handleChange (file, fileList) {
      getAliyunConfig().then((result) => {
        let storeAs = result.data.storePath + "/" + file.name;
        let client = new OSS({
          // region以杭州为例（oss-cn-hangzhou），其他region按实际情况填写。
          region: result.data.region,
          // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
          accessKeyId: result.data.accessKeyId,
          accessKeySecret: result.data.accessKeySecret,
          //stsToken: result.SecurityToken,
          endpoint: result.data.endpoint,// 自己的域名
          bucket: result.data.bucketName,//你的 OSS bucket 名称
          withCredentials: false
        })
        // storeAs表示上传的文件夹 , file表示上传的文件
        client.multipartUpload(storeAs, file.raw, {
          progress: (p) => {
            // 上传进度
            file.percentage = p * 100
          }
        }).then((result) => {
          console.log(result)
          /**
           * 设置本地上传成功的回调
           */
          this.imageUrl = result.res.requestUrls
           this.handleSuccess(this.imageUrl);
        }).catch((err) => {
          console.log(err)
        })
      }).catch((err) => {
        console.log(err)
      })
    },
    handleBeforeUpload(){
      
    }
  }
}
</script>

<style scoped>
</style>